package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/** 解决feign远程调用丢失请求头，
 *  导致远程调用的服务，不能识别是否登录了
 * @Author ShiJieLin
 * @Date 2022/4/30 9:50
 * @Version 1.0
 */
@Configuration
@Slf4j
public class GuliFeignConfig {

    /** feign远程调用不会携带请求头，将当前请求的请求头
     *  给重新赋予到feign中
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                // 1.从Spring中的工具类中取出当前的请求;使用的方式ThreadLocal
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(null != requestAttributes){

                    HttpServletRequest request = requestAttributes.getRequest();
                    /** 2.判断请求是否为null，因为RequestContextHolder
                     *    是ThreadLocal，在多线程下会失效
                     */
                    if(null != request){
                        String cookie = request.getHeader("Cookie");
                        requestTemplate.header("Cookie", cookie);
                    }else {
                        log.info("GuliFeignConfig------------> request请求为null");
                    }
                }
            }
        };
        return requestInterceptor;
    }
}
